import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import Category


# 类型视图
# Create your views here.
@xframe_options_exempt
def index(request):
    return render(request, "category/index.html")


def category_list(request):
    result = {"status": 1, "msg": "操作失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 5)
        search = data.get("search")

        categories = Category.objects.filter(is_delete=0)
        if search and search != "":
            categories = categories.filter(name__icontains=search)
        cg_count = categories.count()
        paginator = Paginator(categories.order_by("-create_time"), limit)     # 每页多少条数据
        try:
            categories = paginator.page(page)        # 返回 page（页数）的数据
        except PageNotAnInteger:
            categories = paginator.page(1)           # 第一页
        except EmptyPage:
            categories = paginator.page(paginator.num_pages)  # 最后一页

        data_list = []
        for i in range(len(categories)):
            data_list.append({
                "No": i+1,
                "id": categories[i].id,
                "name": categories[i].name,
                "remark": categories[i].remark,
                "create_time": str(categories[i].create_time).split(".")[0],
            })

        result["data"] = data_list
        result["data_count"] = cg_count
        result["status"] = 0    # layui parseData status=0 才认为是成功
        result["msg"] = "用户列表查询成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def category_add(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            remark = data.get("remark")
            cg_exist_count = Category.objects.filter(name=name).count()
            if cg_exist_count > 0:
                result["msg"] = "该分类名称已存在！"
                return JsonResponse(result)
            new_cg = Category.objects.create(name=name, remark=remark)
            new_cg.save()
            result["status"] = 1
            result["msg"] = "物料分类添加成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        return render(request, "category/add.html")


@xframe_options_exempt
def category_edit(request, cg_id=None):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            remark = data.get("remark")
            category = Category.objects.filter(id=int(cg_id), is_delete=0).first()
            if not category:
                result["msg"] = "请确认分类是否存在！"
                return JsonResponse(result)

            if category.name != name:
                name_exist = Category.objects.filter(~Q(id=int(cg_id)), name=name, is_delete=0).first()
                if name_exist:
                    result["msg"] = "该分类名称已存在!"
                    return JsonResponse(result)
                category.name = name
            if category.remark != remark:
                category.remark = remark
            category.save()
            result["status"] = 1
            result["msg"] = "分类信息更新成功!"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        category = Category.objects.filter(id=int(cg_id), is_delete=0).first()
        return render(request, "category/edit.html", {'category': category})


def category_del(request, cg_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            category = Category.objects.filter(id=int(cg_id), is_delete=0).first()
            if category:
                category.is_delete = 1
                category.save()
                result["status"] = 1
                result["msg"] = "分类删除成功!"
            else:
                result["msg"] = "请确认分类是否存在!"
        except Exception as e:
            print(e)
    return JsonResponse(result)

